#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){
	
	if(argc==1){
		puts("Usage: ./konvertera_bild pjas_namn");
		return 1;
	}
	
	char pixels[60*60];
	char filnamn[64];
	char filnamnut[64];
	strcpy(filnamn, argv[1]);
	strcpy(filnamn+strlen(argv[1]), ".ppm");
	strcpy(filnamnut, argv[1]);
	strcpy(filnamnut+strlen(argv[1]), ".h");
	FILE* fp = fopen(filnamn, "rb");
	FILE* fput = fopen(filnamnut, "w");
	
	//Hoppa över .ppm-headern
	while(getc(fp)!='\n');
	while(getc(fp)!='\n');
	while(getc(fp)!='\n');
	
	//Konvertera svart=0, vit=1, blått=2
	int i;
	for(i=0; i<60*60; i++){
		unsigned char buffer[3];
		fread(buffer, 1, 3, fp);
		
		if (buffer[2] == 0)
			pixels[i] = 0;
		else if (buffer[0] == 0xff)
			pixels[i] = 1;
		else
			pixels[i] = 2;
	}
	
	i=-1;
	while(pixels[++i]==2);
	int start_x = i%60;
	int start_y = i/60;
	fprintf(fput, "static const Bit_farg %s[   ] = {", argv[1]); // Storleken sätts senare i koden..
	
	char innan=pixels[i-1];
	char senaste=pixels[i];
	int senaste_andring=i;
	int len=1;
	int antal=0;
	for(i=i+1; i<60*60; i++, len++){
		if(pixels[i]!=senaste){
			static const char tabell[3][3] = {{-1, 0, 1}, {0, -1, 1}, {0, 1, -1}};
			if (antal!=0) putc(',', fput);
			fprintf(fput, "{%d,%d}", len, tabell[innan][senaste]);
			senaste_andring=i;
			len=0;
			innan=senaste;
			senaste=pixels[i];
			antal++;
		}
	}
	fprintf(fput, "};\nstatic const char %s_[4] = {%d,%d,%d,%d};\nstatic const short %s_l = %d;\n", argv[1], start_x, start_y, senaste_andring%60, senaste_andring/60, argv[1], antal);
	fseek(fput, strlen(argv[1])+23, SEEK_SET);
	fprintf(fput, "%d", antal);
	fclose(fp);
	fclose(fput);
}
